package frontend.network.rmi;

import interfaces.game.IEntity;
import interfaces.rmi.client.IClientCallBack;
import interfaces.rmi.server.IServerApi;

import java.rmi.NotBoundException;
import java.rmi.RemoteException;
import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;
import java.rmi.server.UnicastRemoteObject;
import java.util.Collection;

import backend.network.server.Server;

public class Client extends UnicastRemoteObject implements IClientCallBack
{
	private static final long serialVersionUID = 1L;
	private static final String NAME = "Bob";
	private static final String HOST = "localhost";
	private static final int PORT = 1099;
	private static Registry registry;

	public Client() throws RemoteException
	{
		super();

		registry = LocateRegistry.getRegistry(HOST, PORT);
		IServerApi remoteApi = null;

		try
		{
			remoteApi = (IServerApi) registry.lookup(Server.NAME);
			for (int i = 1; i <= 3; i++)
			{
				// System.out.println("counter = " + remoteApi.incrementCounter(new Data(1)).getValue());
				Thread.sleep(100);
			}
		} catch (NotBoundException e)
		{
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (InterruptedException e)
		{
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		remoteApi.login(this, NAME);
		System.out.println("Successfully connected to " + remoteApi);

		new Thread(new Runnable()
		{
			@Override
			public void run()
			{
				while (true)
				{
					try
					{
						Thread.sleep(1000);
					} catch (InterruptedException e)
					{
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}
			}
		}).start();
	}

	@Override
	public void chat(String message) throws RemoteException
	{
		System.out.println("IMMA CHATTIN LULZ I GET: " + message);
	}

	@Override
	public void joinMessage(String name) throws RemoteException
	{
		// System.out.println("new player: " + name);
	}

	@Override
	public void exitMessage(String name) throws RemoteException
	{
		// System.out.println("player left: " + name);

	}

	@Override
	public void sendMessage(String name, String s) throws RemoteException
	{
		// System.out.println("player " + name + ": " + s);
	}

	@Override
	public long getTime() throws RemoteException
	{
		// TODO Auto-generated method stub
		return 0;
	}

	@Override
	public long pushUpdates(Collection<IEntity> updates) throws RemoteException
	{
		System.out.println("Got " + updates.size() + " updates...");
		return 0;
	}

}